import router from './router';
import store from './store';
import { getToken } from '@/utils/auth';
import { Toast } from 'vant';

// 白名单
const whiteList = ['/login', '/dashboard'];
const hasUserRole = true; // 验证用户权限

router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' });
    } else {
      if (hasUserRole && store.getters.roles.length === 0) {
        store.dispatch('GetInfo').then(res => {
          const roles = res.roles;
          store.dispatch('GenerateRoutes', { roles }).then(() => {
            router.addRoutes(store.getters.addRouters);
            next({ ...to, replace: true });
          });
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            Toast('登录失效，请稍后重新登录');
            next({ path: '/' });
          });
        });
      } else {
        // TODO 用用户的权限去跟路由当前权限【to.meta.rules】作对比
        // TODO 如果用户权限中有路由当前可允许进入的全选，就放行
        to.meta.title && (document.title = to.meta.title);
        next();
      }
    }
  } else {
    /* 没有登录 */
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      to.meta.title && (document.title = to.meta.title);
      next();
    } else {
      next('/login'); // 否则全部重定向到登录页
    }
  }
});

router.afterEach(() => {
});
